package com.ciwong.mobilepay.weixin;

import android.content.Context;

import com.alipay.sdk.app.m;
import com.ciwong.mobilepay.bean.OrderInfo;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.modelpay.PayResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;


/**
 * 微信支付助手 Created by res-dlzhou on 2015/9/10.
 */
public class WxPayHelper
{
    private volatile static WxPayHelper instance;

    public static WxPayHelper getInstance()
    {
        if (instance == null)
        {
            synchronized (WxPayHelper.class)
            {
                if (instance == null)
                {
                    instance = new WxPayHelper();
                }
            }
        }
        return instance;
    }

    /** 用于初始化相关 */
    private Context mContext;

    /** 支付回调监听 */
    private WxPayListener mListener;

    /** 微信支付API */
    private IWXAPI mPayIWXAPI;

    /** 微信支付响应 */
    private PayResp resp;

    /** 默认为false，true时须要对结果进行处理 */
    private boolean isNeedDealWithResult = false;

    /**
     * 初始化
     * 
     * @param context
     * @param listener
     * @param appId
     */
    public void initPay(Context context, WxPayListener listener, String appId)
    {
        this.mContext = context;
        this.mListener = listener;
        mPayIWXAPI = WXAPIFactory.createWXAPI(mContext, null);
        mPayIWXAPI.registerApp(appId);
    }

    /**
     * 获取微信支付API
     * 
     * @return
     */
    public IWXAPI getIWXAPI()
    {
        return mPayIWXAPI;
    }

    /**
     * 
     * 是否安装微信
     * 
     * @return 是否安装微信
     */
    public boolean isWXAppInstalled()
    {
        return mPayIWXAPI != null && mPayIWXAPI.isWXAppInstalled() ? true
                : false;
    }

    /**
     * 调起支付
     * 
     * @param payReq
     */
    private void sendReq(PayReq payReq)
    {
        // msgApi.registerApp(WxpayConfig.APP_ID);
        mPayIWXAPI.sendReq(payReq);
    }

    /**
     * 获取微信支付客户端
     * 
     * @param order
     *            微信订单信息
     */
    public void sendReq(OrderInfo order)
    {
        PayReq req = new PayReq();
        req.appId = order.getAppid();
        req.nonceStr = order.getNoncestr();
        /* req.packageValue = order.getPackageValue(); */
        req.packageValue = "Sign=WXPay";
        req.partnerId = order.getPartnerid();
        req.prepayId = order.getPrepayid();
        req.timeStamp = order.getTimestamp();
        req.sign = order.getSign();
        sendReq(req);
    }

    /**
     * 处理WXEntryActivity类回调的onReq结果
     * 
     * @param baseReq
     */
    public void dealWithWeixinOnResp(BaseReq baseReq)
    {

        switch (baseReq.getType())
        {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
                break;
            default:
                break;
        }
    }

    /**
     * 处理WXEntryActivity类回调的onResp结果
     * 
     * @param baseResp
     */
    public void dealWithWeixinOnResp(BaseResp baseResp)
    {

        if (baseResp != null)
        {
            resp = (PayResp) baseResp;
            isNeedDealWithResult = true;
        }
    }

    /**
     * 微信结果回调(此方法须在onResume()方法中执行)
     */
    public void onResumeResultData()
    {
        if (isNeedDealWithResult)
        {
            isNeedDealWithResult = false;
            // 微信支付命令
            if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX)
            {
                switch (resp.errCode)
                {
                // 支付成功
                    case BaseResp.ErrCode.ERR_OK:
                        mListener.onWXPaySucc(resp.errStr);
                        break;
                    // 支付错误
                    case BaseResp.ErrCode.ERR_COMM:
                        mListener
                                .onWXPayFailure(resp.errCode,
                                        "支付错误:"+resp.errStr);
                        //签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
                        break;
                    // 取消支付(无需处理。发生场景：用户不支付了，点击取消，返回APP)
                    case BaseResp.ErrCode.ERR_USER_CANCEL:
                        mListener.onWXPayCencel();
                        break;

                    default:
                        break;
                }
            }
        }
    }

    /**
     * 和 回收资源
     * 
     */
    public void release()
    {
        if (mPayIWXAPI != null)
        {
            mPayIWXAPI.unregisterApp();
            mPayIWXAPI = null;
        }
        resp = null;
        mListener = null;
        instance = null;
    }
}
